<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-fill-left.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="建模工具," />





  <link rel="alternate" href="/atom.xml" title="我的笔记本" type="application/atom+xml" />






<meta name="description" content="导读终于，使用Ubuntu系统的我遇到了最尴尬的问题：建模工具Matlab没有linux发行版。虽然可以使用wine勉强跑起来，但毕竟不是运行在Windows内核下，所以往往有很多事情都非常尴尬。所以，我看上了这一款：octave。不仅支持Ubuntu，还能够兼容Matlab，是非常不错的替代品。">
<meta property="og:type" content="article">
<meta property="og:title" content="建模工具：octave">
<meta property="og:url" content="https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/index.html">
<meta property="og:site_name" content="我的笔记本">
<meta property="og:description" content="导读终于，使用Ubuntu系统的我遇到了最尴尬的问题：建模工具Matlab没有linux发行版。虽然可以使用wine勉强跑起来，但毕竟不是运行在Windows内核下，所以往往有很多事情都非常尴尬。所以，我看上了这一款：octave。不仅支持Ubuntu，还能够兼容Matlab，是非常不错的替代品。">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/octave%E7%95%8C%E9%9D%A2.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/octave%E4%BF%9D%E5%AD%98%E6%95%B0%E6%8D%AE.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E5%9F%BA%E6%9C%AC%E6%8A%98%E7%BA%BF%E5%9B%BE.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E6%9B%B4%E6%8D%A2%E6%A0%B7%E5%BC%8F.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E6%9B%B4%E6%8D%A2%E9%A2%9C%E8%89%B2.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E6%95%A3%E7%82%B9%E5%9B%BE.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E6%9F%B1%E7%8A%B6%E5%9B%BE.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E7%AD%89%E9%AB%98%E7%BA%BF.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E6%9E%81%E5%9D%90%E6%A0%87.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E8%9E%BA%E6%97%8B%E7%BA%BF.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E9%A5%BC%E7%8A%B6%E5%9B%BE.png">
<meta property="og:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/%E7%AA%81%E5%87%BA%E9%83%A8%E5%88%86%E5%85%83%E7%B4%A0%E7%9A%84%E9%A5%BC%E5%9B%BE.png">
<meta property="article:published_time" content="2020-07-26T15:23:00.000Z">
<meta property="article:modified_time" content="2020-09-19T00:02:36.227Z">
<meta property="article:author" content="sakebow">
<meta property="article:tag" content="建模工具">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/octave%E7%95%8C%E9%9D%A2.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://sakebow.github.io/2020/07/26/人工智能/理论基础/建模工具：octave/"/>



<meta name="google-site-verification" content="gmKmVpWaqN85ipDFNNCd2AweYJjcTFrVxCKCy36wueo" />
<script>
var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?1d2c90caa02c073d8ebaa116ab3027fb";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script>


  <title>建模工具：octave | 我的笔记本</title>
  








  
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <script type="text/javascript" src="/js/src/custom.js"></script>
  
<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/sakebow" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub">
	  <svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"
	    style="fill:#64CEAA; color:#fff; position: fixed; top: 0; border: 0; right: 0; z-index: 999;">
	    <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
		<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
		  fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
		<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
		  fill="currentColor" class="octo-body"></path>
	  </svg>
	</a>
	<style>
	  .github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}
	  @keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}
	  @media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}
	</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">我的笔记本</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">一只干什么都会失败但是很不想放弃的科研狗</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="sakebow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/icon/UN.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我的笔记本">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">建模工具：octave</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-26T23:23:00+08:00">
                2020-07-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/" itemprop="url" rel="index">
                    <span itemprop="name">人工智能</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  5.8k字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  21分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="导读"><a href="#导读" class="headerlink" title="导读"></a>导读</h2><p><strong>终于，使用<code>Ubuntu</code>系统的我遇到了最尴尬的问题：建模工具<code>Matlab</code>没有<code>linux</code>发行版。虽然可以使用<code>wine</code>勉强跑起来，但毕竟不是运行在<code>Windows</code>内核下，所以往往有很多事情都非常尴尬。所以，我看上了这一款：<code>octave</code>。不仅支持<code>Ubuntu</code>，还能够兼容<code>Matlab</code>，是非常不错的替代品。</strong></p>
<a id="more"></a>
<h2 id="界面展示"><a href="#界面展示" class="headerlink" title="界面展示"></a>界面展示</h2><p>先看看<code>octave</code>的软件界面，体验一下吧。</p>
<p><img src="https://sakebow.gitee.io/images/%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0/octave%E7%95%8C%E9%9D%A2.png" alt="octave界面"></p>
<p>可以看到左边由上至下依次是：文件目录、工作空间和历史记录，而左边则是命令行界面。</p>
<p>是不是非常熟悉？没错，这简直不能再像<code>Matlab</code>了。即使顶部功能菜单并没有<code>Matlab</code>那么丰富，却也足够了。</p>
<h2 id="更换命令行"><a href="#更换命令行" class="headerlink" title="更换命令行"></a>更换命令行</h2><p>如果你有丰富的<code>shell</code>编程经验，那么你应该对这个<code>&gt;&gt;</code>非常熟悉。<code>Matlab</code>使用的是<code>&gt;&gt;</code>，<code>MySQL</code>使用的是<code>&gt;</code>，<code>sqlplus</code>（<em><code>Oracle</code></em>）使用的是<code>&gt;</code>，<code>Python</code>使用的是<code>&gt;&gt;&gt;</code>，<code>Ubuntu</code>普通用户使用的是<code>$</code>，<code>Ubuntu</code>超管使用的是<code>#</code>……</p>
<p>如果说你用惯了想要换，还是可以的。直接输入</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 这段字符串复制自我的Ubuntu终端</span></span><br><span class="line">PS1("sakebow@Lenovo-V310-14IKB:~$ ")</span><br></pre></td></tr></table></figure>
<p>这样就能够保持和终端一模一样的风格了。当然为了区分也可以改称其他的，比如</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> ……懂的都懂……</span></span><br><span class="line">PS1("お兄ちゃん、頑張るね、大好きだよ❤　")</span><br></pre></td></tr></table></figure>
<h2 id="基于Linux的特点"><a href="#基于Linux的特点" class="headerlink" title="基于Linux的特点"></a>基于<code>Linux</code>的特点</h2><p>当然，因为开源免费的<code>octave</code>是使用<code>C</code>语言基于<code>Linux</code>系统开发的，所以也会保留一些<code>Linux</code>系统的命令。比如：</p>
<ul>
<li><code>pwd</code>显示当前所在文件夹</li>
<li><code>ls</code>显示当前文件夹中所有的文件</li>
<li><code>cd</code>跳转到制定文件夹</li>
<li><code>exit</code>退出程序</li>
</ul>
<p>即使是安装在<code>Windows</code>系统下的<code>octave</code>也是能够使用这些命令的。</p>
<h2 id="清空矩阵"><a href="#清空矩阵" class="headerlink" title="清空矩阵"></a>清空矩阵</h2><p>在<code>Ubuntu</code>系统中你可以直接使用<code>Ctrl+L</code>清空命令行。所有的指令会存在历史记录<code>Command History</code>栏内</p>
<p>当然你也可以输入<code>clc</code>并回车就能够清空命令行</p>
<h2 id="快速矩阵"><a href="#快速矩阵" class="headerlink" title="快速矩阵"></a>快速矩阵</h2><blockquote>
<p>这些<code>Octave</code>内置的快速矩阵摘自摘自<a href="https://www.youtube.com/watch?v=X0xLTKRWPgo&amp;list=PL1A2CSdiySGJ6oZe6" target="_blank" rel="noopener">油土鳖上一位印度阿三的教程</a>（<em>英语略微有一些咖喱味，但已经很不错了</em>）</p>
</blockquote>
<script type="math/tex; mode=display">
ones(n, m) = \left[
  \begin{matrix}
    1, \cdots, 1\\\vdots\\
    1, \cdots, 1
  \end{matrix}
\right]_{n\times m}
\\
zeros(n, m) = \left[
  \begin{matrix}
    0, \cdots, 0\\\vdots\\
    0, \cdots, 0
  \end{matrix}
\right]_{n\times m}
\\
eye(n) = \left[
  \begin{matrix}
    1, 0, 0, \cdots, 0\\
    0, 1, 0, \cdots, 0\\
    0, 0, 1, \cdots, 0\\\vdots\\
    0, 0, 0, \cdots, 1
  \end{matrix}
\right]_n = E
\\
eye(n, n + 1) = \left[
  \begin{matrix}
    1, 0, 0, \cdots, 0, 0\\
    0, 1, 0, \cdots, 0, 0\\
    0, 0, 1, \cdots, 0, 0\\\vdots\\
    0, 0, 0, \cdots, 1, 0
  \end{matrix}
\right]_{n\times(n+1)}
\\</script><p>而<code>rand(n,m)</code>则是生成<strong>n行m列</strong>的<strong>均匀分布随机数矩阵</strong>（<em>uniformly random matrix</em>），每个数字都是<strong>介于0到1之间的7位小数</strong>，且每个数字出现概率服从均匀分布$U(0, 1)$；</p>
<p><code>randn(n,m)</code>是生成一共<strong>n列m行</strong>的<strong>正态分布随机数矩阵</strong>（<em>normally random matrix</em>），每个数字服从正态分布$N(0, 1)$。乍一看这组数据毫无特点，实际上是$P(\mu-\sigma&lt;x&lt;\mu+\sigma)\approx0.6826$。这也就说明了为什么数字里面会有<strong>大于$1$和小于$-1$的数字了</strong></p>
<h2 id="矩阵构造"><a href="#矩阵构造" class="headerlink" title="矩阵构造"></a>矩阵构造</h2><p>在<code>C</code>、<code>C++</code>、<code>Java</code>、<code>C#</code>等等语言中构造矩阵永远是一个很难受的工程，拿<code>Java</code>中的<code>List&lt;List&lt;?&gt;&gt;</code>来说，向其中添加元素是一项无比复杂的工程。</p>
<p>而在<code>octave</code>和<code>Matlab</code>中，就只需要使用</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; s = [<span class="number">1</span>, <span class="number">2</span>; <span class="number">3</span>, <span class="number">4</span>]</span><br><span class="line">s = </span><br><span class="line">  <span class="number">1</span> <span class="number">2</span></span><br><span class="line">  <span class="number">3</span> <span class="number">4</span></span><br></pre></td></tr></table></figure>
<p>在这里你可以使用<strong>逗号</strong>作为分割符，也可以仅用<strong>空格</strong>作为分割符。</p>
<p>如果你要用<strong>克莱姆法则</strong>解多元一次方程组，那么就需要几个矩阵拆拆解解。这个时候可以把一整个矩阵当作数字：</p>
<ul>
<li><code>[A B]</code>像是<code>[1 2]</code>，将两个数字横着拼起来</li>
<li><code>[A; B]</code>则是<code>[1; 2]</code>，将两个数字竖着拼起来</li>
<li><code>A&#39;</code>是矩阵的转置，就是$A^T$</li>
</ul>
<p>当然，我们还有矩阵的选择：</p>
<ul>
<li><code>S(m, n)</code>是选取矩阵<code>S</code>中<strong>第m行第n列</strong>的一个元素</li>
<li><code>S(m, [x, y, z])</code>是选择矩阵中<strong>第m行第x、y、z列</strong>的一共三个元素。如果还需要添加元素则在<code>[]</code>内追加</li>
<li><em>下方冒号表达式继续介绍</em></li>
</ul>
<h2 id="冒号表达式"><a href="#冒号表达式" class="headerlink" title="冒号表达式"></a>冒号表达式</h2><p>如果你熟悉<code>C</code>、<code>C++</code>、<code>Java</code>、<code>C#</code>等等（<em><code>Python</code>除外</em>），你应该会经常使用到冒号表达式，即是：</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 输出该学生是否可以购买打折的火车票</span></span><br><span class="line"><span class="built_in">cout</span> &lt;&lt; 学生.学生证 === null ? <span class="string">"火车票不能打折"</span> : <span class="string">"火车票可以打折"</span> &lt;&lt; <span class="built_in">endl</span>;</span><br></pre></td></tr></table></figure>
<p>但是在<code>octave</code>和<code>Matlab</code>就完全不一样了。冒号表达式会这么用：<code>start[:step]:end</code>，即创建一个从<code>start</code>到<code>end</code>的数组，其中每个数字之间间隔<code>step</code>，默认<code>step</code>值为<strong>1</strong>，即依次递增。</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; s = <span class="number">1</span> : <span class="number">5</span></span><br><span class="line">&gt;&gt; <span class="built_in">ans</span> =</span><br><span class="line">[<span class="number">1</span> <span class="number">2</span> <span class="number">3</span> <span class="number">4</span> <span class="number">5</span>]</span><br><span class="line">&gt;&gt; </span><br><span class="line">&gt;&gt; s = <span class="number">1</span>:<span class="number">3</span>:<span class="number">10</span></span><br><span class="line">&gt;&gt; <span class="built_in">ans</span> =</span><br><span class="line">[<span class="number">1</span> <span class="number">4</span> <span class="number">7</span> <span class="number">10</span>]</span><br></pre></td></tr></table></figure>
<p>当然冒号不止这一个用途。刚刚我们说了矩阵的构造，在矩阵中冒号还能够用作选择器。</p>
<p>我们在选择矩阵中元素的时候会使用一个<strong>数组</strong>作为范围，而如果这个范围<strong>正好</strong>可以用冒号表示的时候，就可以是这样：</p>
<ul>
<li><p><code>S(m, [start : end])</code>，也就是说选取<strong>第m行从start开始到end结束的所有元素</strong></p>
</li>
<li><p>如果没有规定<code>start</code>和<code>end</code>，也就像是：<code>S(m, :)</code>，那么就是选取<strong>第m行一整行</strong></p>
</li>
</ul>
<h2 id="个数计算"><a href="#个数计算" class="headerlink" title="个数计算"></a>个数计算</h2><p><code>Java</code>中，对集合使用<code>size()</code>方法求集合内元素个数，对数组使用<code>length()</code>方法求数组内元素个数。</p>
<p>在<code>octave</code>中，我们两个都可以用，但是<code>size()</code>方法返回的是行和列两个数字，而<code>length</code>方法则是从<code>size()</code>方法返回的两个数字中选择一个最大的。举个例子：</p>
<p>假设你这个时候又闲着没事创建了一个随机数组<code>rand(5, 1)</code>，那么<code>size()</code>方法返回的是<code>[5 1]</code>两个数字，前者是行数，后者是列数；而<code>length()</code>方法返回的是<strong>5</strong>，是<strong>5</strong>和<strong>1</strong>中较大的数。</p>
<p>同样的，如果你只有一个数组<code>[1 2 4]</code>，<code>size()</code>方法返回的依然是<code>[1 3]</code>两个数，而<code>length()</code>方法就返回<strong>3</strong>。</p>
<h2 id="其他数学函数"><a href="#其他数学函数" class="headerlink" title="其他数学函数"></a>其他数学函数</h2><ul>
<li><code>ceil(x)</code> - 取比x大的第一个最近的整数，即向上取整</li>
<li><code>floor(x)</code> - 取比x小的第一个最近的整数，即向下取整</li>
<li><code>round(x)</code> - 取距离x最近的一个整数。如果$x=0.7$，则结果为$1$；如果$x=0.3$，则结果为$0$</li>
<li><code>max(x)</code> / <code>min(x)</code> - 取一个数组中最大/最小的数</li>
</ul>
<p>对于<code>max(x)</code>和<code>min(x)</code>在官方给的说明里面指明的是vector，也就是说这个函数同样适用于矩阵、向量等等。但是实际测试的时候是这样的：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt; <span class="built_in">rand</span>(<span class="number">5</span>, <span class="number">3</span>)</span><br><span class="line"><span class="built_in">ans</span> =</span><br><span class="line"> <span class="number">0.097667</span>   <span class="number">0.295360</span>   <span class="number">0.710065</span></span><br><span class="line"> <span class="number">0.858128</span>   <span class="number">0.141471</span>   <span class="number">0.729432</span></span><br><span class="line"> <span class="number">0.073253</span>   <span class="number">0.503299</span>   <span class="number">0.379730</span></span><br><span class="line"> <span class="number">0.329683</span>   <span class="number">0.839168</span>   <span class="number">0.076656</span></span><br><span class="line"> <span class="number">0.662468</span>   <span class="number">0.514276</span>   <span class="number">0.020735</span></span><br><span class="line">&gt;&gt;</span><br><span class="line">&gt;&gt; <span class="built_in">min</span>(<span class="built_in">ans</span>)</span><br><span class="line"><span class="built_in">ans</span> =</span><br><span class="line"> <span class="number">0.073253</span>   <span class="number">0.141471</span>   <span class="number">0.020735</span></span><br></pre></td></tr></table></figure>
<p>不难发现，对比的时候将一整列作为一个数组进行纵向的对比，每一列选出了一个最小的。在上面这个例子中，数组<code>ans[0..4][0..2]</code>每一列选出了最小的，也就是<code>ans[2, 0]</code>、<code>ans[1, 1]</code>和<code>ans[3, 2]</code>。<code>max(ans)</code>也是一样的算法，只不过会每列找出一个最大的。</p>
<h2 id="数据集的导入和导出"><a href="#数据集的导入和导出" class="headerlink" title="数据集的导入和导出"></a>数据集的导入和导出</h2><p>如果有一天我们使用计算机去证明歌德巴赫猜想，把所有的数字塞进去日复一日地算，终于算出来了一大批数字。我们不可能使用人工一个个抄下来，肯定是让计算机自己保存。这个时候就用<code>save</code>命令让计算机保存所有的数字。</p>
<p>例如，我现在弄出了很大一批随机数<code>randn(1000, 1000)</code>，但是我突然发现笔记本电不够了，得保存下来。就这么使用：<code>save ${文件名} ${变量名}</code>，意思就是：将变量的值保存在指定中。当然你也可以指定别的后缀名，比如我这里选择：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">save <span class="built_in">randn</span>.json <span class="built_in">ans</span></span><br></pre></td></tr></table></figure>
<p>于是就有了如下效果：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/octave保存数据.png" alt="保存了十万条随机数"></p>
<p>但是呢，为了能够更直观地区分各个文件，我们尽可能按照大家默认的规矩来，这里推荐万能的<code>.csv</code>文件；官方更是推荐使用<code>.mat</code>文件。更何况，我这里导出的文件并不符合<code>json</code>文件的编写规范。</p>
<p>就像是<code>Java</code>的导包一样，我们会使用<code>import</code>导入一整个<code>jar</code>包。而在<code>octave</code>中，我们将会使用<code>load</code>命令导入文件。</p>
<p>如果再次使用，我们就使用<code>load</code>命令，即：<code>load randn.dat</code>（<em>我这里是.json</em>）</p>
<p><strong>看起来很简单？我们再来点奇葩的：</strong></p>
<p>有一天你们哥几个凑一起跑数据，结果突然发现两个人风格极其相近以至于命名都完全一样。现在重新改已经很头疼了，怎么办？</p>
<p>我们就用<strong>临时文件</strong>。</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">% 创建临时文件</span></span><br><span class="line">f = tmpfile</span><br><span class="line"><span class="comment">% 将变量存入临时文件</span></span><br><span class="line">save f variable</span><br><span class="line"><span class="comment">% &#123;</span></span><br><span class="line">  拿同名变量处理一大堆事情</span><br><span class="line">&#125; <span class="comment">%</span></span><br><span class="line"><span class="comment">% 读取临时文件</span></span><br><span class="line">load f</span><br><span class="line"><span class="comment">% 这个时候同名变量就被覆盖了</span></span><br></pre></td></tr></table></figure>
<p>打个比方的话，就像是<code>C</code>语言的<strong>局部变量</strong>和<strong>全局变量</strong>一样。</p>
<p>当然，这只是一个非常极端的例子，我们强烈建议各小组之间事先商量好再码字，正如<code>SpringBoot</code>所倡导的：“<strong>约束大于业务</strong>”、“<strong>习惯大于编码</strong>”</p>
<h2 id="统计图绘制"><a href="#统计图绘制" class="headerlink" title="统计图绘制"></a>统计图绘制</h2><p>统计图必定是有数据支持的，但是现在没有数据……那么就随机生成吧：<code>rand(1, 100)</code>。于是工作空间中就有了<code>ans</code>这个变量，同时还有了一个共<strong>1行</strong>、<strong>100列</strong>的矩阵，也就是数组。</p>
<p>然后，我们就画图：<code>plot(ans)</code>，于是产生了一个很简单的折线图：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/基本折线图.png" alt="最简单的折线图"></p>
<p>因为是随机生成的数字，所以也看不出什么规律。</p>
<p>你可能会有点惊讶，为什么明明只有<code>ans</code>一个变量，谈不上所谓因变量和自变量，他是怎么画出来的？实际上这里是将<strong>下标</strong>作为横坐标、<strong><code>ans</code>的值</strong>作为纵坐标画出来的。</p>
<h2 id="统计图绘制样式"><a href="#统计图绘制样式" class="headerlink" title="统计图绘制样式"></a>统计图绘制样式</h2><p>如果说你不需要折线图，而是散点图，那么就更改绘图样式吧：<code>plot(ans, &#39;*&#39;)</code></p>
<p><img src="https://sakebow.gitee.io/images/机器学习/更换样式.png" alt="把折线图换成散点图"></p>
<p>当然你觉得<code>*</code>不太美观的话也可以换成中文的<code>·</code>（<em>中文输入下波浪线按钮不加<code>shift</code></em>）或者日文的<code>・</code>（<em>日文输入下问号按钮不加<code>shift</code></em>）</p>
<p>为了防止很多图像看混了，可以使用不同的颜色标记：<code>plot(ans, &#39;1&#39;)</code></p>
<p><img src="https://sakebow.gitee.io/images/机器学习/更换颜色.png" alt="更改颜色"></p>
<p>各种各样的数字代表了各种各样的<strong>颜色</strong>，而各种各样的字符代表了各种各样的<strong>描点</strong>。</p>
<p>如果你什么都不写，那么默认就是使用<code>-</code>，也就是折线图。</p>
<h2 id="散点图"><a href="#散点图" class="headerlink" title="散点图"></a>散点图</h2><p>好吧，用<code>plot</code>画出来的散点图多少还是有点点奇怪。那么我们干脆用专门画散点图的方法：<code>scatter</code>。</p>
<p>还是一样的，我们拿到了一组数据：<code>x = randn(1, 100)</code>，另外我们再来一组数据：<code>y = randn(1, 100)</code>，然后画出随机散点图：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/散点图.png" alt="散点图"></p>
<p>同样的，我们能够使用家参数的方式改变图像的样式：<code>scatter(x, y, &#39;*&#39;)</code>。只不过这里支持的字符就比较少了，经测试似乎仅支持将圆圈更换为<code>*</code>。</p>
<h2 id="柱状图"><a href="#柱状图" class="headerlink" title="柱状图"></a>柱状图</h2><p>柱状图也是一种重要的工具，在统计总数并比较多条数据的差值时用得多。就比如100个服从正态分布的随机数构成的柱状图中，能够清晰地看出各个概率之间分布的差值：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/柱状图.png" alt="柱状图"></p>
<p>我们知道，$P(0-1&lt;x&lt;0+1)\approx0.6826$，所以数据比较倾向于向$(-1, 1)$这个区间集中。</p>
<h2 id="等高线"><a href="#等高线" class="headerlink" title="等高线"></a>等高线</h2><p>就像是地理的等高线、电磁场的等势线一样，存在的目的就是为了说明哪一段是数值上相等的。在绘制的时候，我们需要提供一个至少<strong>两行两列</strong>的矩阵，然后就由<code>contour</code>方法寻找矩阵中值算出等高线。</p>
<p>比如对于$ans=\left[\begin{matrix}1&amp;2\\3&amp;4\\5&amp;6\\7&amp;8\end{matrix}\right]$这个矩阵画出来的等高线就是<code>contour(ans)</code>：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/等高线.png" alt="等高线"></p>
<h2 id="极坐标"><a href="#极坐标" class="headerlink" title="极坐标"></a>极坐标</h2><p>高中我们认识并狠狠地练习了<strong>极坐标</strong>这些题目，所以我们就直接从最简短的开始：$\rho=2\cos\theta$。相信你很清楚这个等式可以化为$x^2+y^2=x$，是以$(1,0)$为圆心、$1$为半径的圆。</p>
<p>那么就确定两个变量：<code>p = linspace(0, 1)</code>和<code>o = linspace(0, 2 * pi)</code></p>
<p><em>注：linspace(x, y) = x:0.01:y，即从x到y中每隔0.01取一个点</em></p>
<p>然后，画极坐标：polar(p, o)</p>
<p>就出现了这样的图：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/极坐标.png" alt="极坐标"></p>
<p>似乎和我们平常见到的直角坐标系不一样。不过没有关系，是不是在很多影视作品中看到类似的？<strong>雷达</strong>嘛。在战场上，你发送了敌机的$(x, y, z)$坐标，<strong>这谁懂啊</strong>。干脆点，报哪个方向方向多少度，往那打。这种情况下极坐标比直角坐标好用多了。</p>
<p>还有其他很有意思的：比如我们将刚刚的<code>p</code>和<code>o</code>调换一下位置，就成了螺旋线。</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/螺旋线.png" alt="螺旋线"></p>
<h2 id="饼状图"><a href="#饼状图" class="headerlink" title="饼状图"></a>饼状图</h2><p>饼状图只是为了查看占比，所以大批量的随机数在这里并不适合作为样本。所以这里就随机生成三个数：<code>ans = randn(1, 3)</code></p>
<p><em>由于饼状图是组内比较，所以只能使用一组数据，即<strong>行向量</strong>或者<strong>列向量</strong>作为参数。如果生成<code>ans = randn(10, 10)</code>作为样本则会报错。使用时还请注意。</em></p>
<p><img src="https://sakebow.gitee.io/images/机器学习/饼状图.png" alt="饼状图"></p>
<p>可以看到，<code>octave</code>拿到数据之后立马进行了权重的计算，最终得出了这个结果。所以我们在实际实验中就只需要把数据整理成<strong>行向量</strong>或者<strong>列向量</strong>传入，<code>octave</code>就能够在一定程度上。</p>
<p>既然饼状图是查看一个部分或者多个部分的占比，为了让图片更清晰，就可以让一些部分联系起来。</p>
<p>时间回溯到你收集猫娘数据的那些日子（<del>别吐槽了，听就是了</del>）</p>
<p>你了解到全世界的猫娘们的年龄从0岁开始往上的数量依次是<code>neko = [16247, 18752, 19165, 17251, 11471, 18714, 10961, 5428, 13725, 8715, 10031, 13298, 8715, 9716, 4562, 9612, 3610]</code>（<em>随手瞎打的</em>）。你想清晰地看出在0到3岁的猫娘占比，于是你使用第二个参数：<code>explode</code>。这个参数应当是一个数组。如果数值为0，则会与下一个块区相接；而如果非0，即使是负数也会明显分开。</p>
<p>于是我们为了清晰地看出0到3岁的小猫娘的数量，我们使用<code>pie (neko, [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])</code>，就会产生这样的效果：</p>
<p><img src="https://sakebow.gitee.io/images/机器学习/突出部分元素的饼图.png" alt="突出部分元素"></p>
<p>可以看到，设置为非零的前三个部分被分开了，占比$8\%+9\%+10\%=27\%$。这是不是比不突出任何元素的饼图看起来更直观呢？</p>
<h2 id="选择支"><a href="#选择支" class="headerlink" title="选择支"></a>选择支</h2><p>当然，作为一门高级语言，选择支是必要的。</p>
<p>如果你是想通过选择支筛选不同年龄段，那么就使用：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> age &lt; <span class="number">3</span>,</span><br><span class="line">  <span class="comment">% filter for age &lt; 3</span></span><br><span class="line"><span class="keyword">elseif</span> age &lt; <span class="number">10</span>,</span><br><span class="line">  <span class="comment">% filter for 3 &lt; age &lt; 10</span></span><br><span class="line"><span class="keyword">else</span>,</span><br><span class="line">  <span class="comment">% filter for age &gt; 10</span></span><br><span class="line"><span class="keyword">end</span>;</span><br></pre></td></tr></table></figure>
<p>这个逗号估计就是在命令划分的时候不太好识别标志加上的。虽然和<code>Java</code>、<code>Python</code>略有出入，但我相信这绝对有他的道理。</p>
<h2 id="循环"><a href="#循环" class="headerlink" title="循环"></a>循环</h2><p><code>while</code>循环相信各位都熟悉得不能再熟悉了。实际上<code>while</code>和<code>if</code>的用法实际上是一样的。毕竟都是判断条件并转入选择支。唯一的区别估计就是<code>if</code>语句能够接<code>else if</code>和<code>else</code>来筛选不同的条件，而<code>while</code>只能始终选择同一个条件。</p>
<p><code>for</code>循环相比<code>while</code>循环又多了一个神奇的功能：将一个集合里的每一个元素创建索引，并这个索引仅作用于<code>for</code>循环中，是区域变量。</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">% 假设nekos里面保存了每只猫娘的年龄(age)和姓名(name)</span></span><br><span class="line"><span class="keyword">for</span> neko = nekos,</span><br><span class="line">  <span class="keyword">if</span> neko.age &gt; <span class="number">10</span>,</span><br><span class="line">    sprintf(<span class="string">"%i"</span>, neko.name)</span><br><span class="line">  <span class="keyword">end</span>;</span><br><span class="line"><span class="keyword">end</span>;</span><br></pre></td></tr></table></figure>
<p>如果你确定这些猫娘有着不同的名字，并且你一定要找到那只叫做“<strong>chocola</strong>”的猫娘（<em>没……没夹带私货……真的！</em>），那么就这么来：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> neko = nekos,</span><br><span class="line">  <span class="keyword">if</span> neko.name == <span class="string">'chocola'</span>,</span><br><span class="line">    sprintf(<span class="string">"%i"</span>, neko.age)</span><br><span class="line">    <span class="keyword">break</span>; <span class="comment">% 跳出一层循环</span></span><br><span class="line">  <span class="keyword">end</span>;</span><br><span class="line"><span class="keyword">end</span>;</span><br></pre></td></tr></table></figure>
<p>有了这个<code>break</code>，一旦找到了<strong>chocola</strong>就会退出并显示她的年龄。</p>
<p>而如果这些猫娘有重名却有着不容的铃铛编号呢？那么就全找出来。</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> neko = nekos,</span><br><span class="line">  <span class="keyword">if</span> neko.name == <span class="string">'chocola'</span>,</span><br><span class="line">    sprintf(<span class="string">"%i"</span>, neko.id)</span><br><span class="line">    <span class="keyword">continue</span>; <span class="comment">% 强制结束本次循环</span></span><br><span class="line">  <span class="keyword">end</span>;</span><br><span class="line"><span class="keyword">end</span>;</span><br></pre></td></tr></table></figure>
<p>有了<code>continue</code>，程序就不会结束，反而是直接结束<code>continue</code>后面的所有步骤，强行结束本次循环。全部显示出来之后我们再对比这些编号是不是我们想要的编号。</p>
<p>和<code>Java</code>、<code>Python</code>等等有着非常多的相似之处呢。即使完全没接触过<code>matlab</code>，相信你们也能用丰富的编程经验理解用法。</p>
<h2 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h2><p>函数看起来非常高端，实际上你可以看成多个普通命令的合集。</p>
<p>函数是有固定的套路的：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> $&#123;<span class="title">variable</span>&#125; = $&#123;<span class="title">function</span> <span class="title">name</span>&#125; <span class="params">($&#123;argument list&#125;)</span></span></span><br><span class="line">  <span class="comment">% to do list</span></span><br><span class="line">endfunction;</span><br></pre></td></tr></table></figure>
<p>但是你得明白：函数毕竟是一个包含了很多行的整体。如果你使用纯命令行编辑整个函数，一旦某个地方有所疏忽，一运行函数就有可能会报错，然后<strong>整个函数重写</strong>。这是相当考验熟练度、耐心和细心的工作。当然，肯定不会让你有这么难受的体验的。</p>
<p><code>octave</code>为了能够在数学处理上由所优势，就决定兼容<code>matlab</code>所使用的<code>.m</code>文件。在这个文件中，我们能够使用各种各样的变量记录函数的定义，这样即使出现了错误我们也能够通过错误信息定位到不正确的地方并修改。这样就避免了整个函数重写的惨痛经历。</p>
<p>如果你只有命令行，或者说只愿意使用命令行，<code>octave</code>也是提供了专门的命令：<code>edit ${file name}</code>。如果是<code>Ubuntu</code>系统，<code>octave</code>将会在<code>~/octave</code>文件夹下创建或者修改文件。在这里尤其注意文件的命名，一方面是因为这样子能够很清晰地弄清楚什么文件保存了什么函数，另一方面也是因为有些文件名是<code>octave</code>内定的<strong>特殊文件</strong>，比如<code>test.m</code>是<code>octave</code>规定的测试文件，其中含有非常多的内置函数和测试函数供用户调用、测试。而如果只是一般的命名就没有什么特殊的，只是会加上很多版权说明，并默认提供一个空函数模板以供用户根据需求修改。</p>
<p>有点难懂？那我们举个例子，主人公还是那个热爱猫娘的你。这次的你尽了全力也没能收集全所有的数据，有些猫娘一被问到年龄就狠狠地挠你的嘴，有些则因为怕生逃掉了，也有些则在接近之前你就被主人当成可疑人物带走了……总之，你虽然找到了20万只猫娘，却只收集了5000条残缺不全的数据，不是掉了这个就是少了那个。但是该寻找的还是要寻找，那就是查清相同年龄里成绩最好和成绩最差的两只猫娘的信息。</p>
<p>在写这个函数之前，我们首先明白几个非常重要的点：</p>
<ul>
<li><code>octave</code>是以<code>matlab</code>为模板创建的全平台兼容的软件，所以有什么不懂可以直接查询<code>matlab</code>的教程；</li>
<li><code>octave</code>与<code>matlab</code>非常相似，都是以<code>C</code>为基础搭建的，所以并没有<strong>面向对象编程</strong>的概念，整个程序就是为了<strong>面向过程</strong>而设定的。</li>
</ul>
<p>所以，我们如果使用<code>octave</code>处理猫娘们的数据的时候，只能把所有想要的全部<strong>手打</strong>或者<strong>通过脚本筛选</strong>，最终达成只包含需要被处理的部分的、单纯列出所有而不是分类整合的数据集。如果是使用各种各样括号分开的<code>json</code>数据则无法被处理为一个个对象，却只能分成许许多多的单条数据。</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">% 文件名：filter.m</span></span><br><span class="line"><span class="comment">% 从一堆数据中寻找最小的数据</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">filter_mini</span> = <span class="title">filter</span><span class="params">(x)</span></span></span><br><span class="line">  ret = x(<span class="number">1</span>)</span><br><span class="line">  <span class="keyword">for</span> <span class="built_in">i</span> = <span class="number">2</span>:<span class="built_in">length</span>(x),</span><br><span class="line">    <span class="keyword">if</span> x(<span class="built_in">i</span>) &lt; ret,</span><br><span class="line">      ret = x(<span class="built_in">i</span>)</span><br><span class="line">    endif;</span><br><span class="line">  endfor;</span><br><span class="line">endfunction;</span><br></pre></td></tr></table></figure>
<p>在这里需要非常注意的是：<strong>一个文件只能编辑一个函数</strong>，<strong>每个函数的名称必须和文件名保持一致</strong>，否则会报警告：<strong>函数名和文件名不匹配</strong>。调用则是很普通的使用文件名即可，代入参数便能得到结果。</p>
<p>可是，我要找出猫娘的<code>id</code>啊，你这只能找出分数欸。那就这样，我们先按照猫娘的<code>id</code>顺序排列，我们找出最大和最小的索引，再从这些索引中找出<code>id</code>就好咯。</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="params">[low, low_index, high, high_index]</span> = <span class="title">filter</span><span class="params">(x)</span></span></span><br><span class="line">  low = x(<span class="number">1</span>); high = x(<span class="number">1</span>); low_index = <span class="number">0</span>; high_index = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> <span class="built_in">i</span> = <span class="number">2</span>:<span class="built_in">length</span>(x),</span><br><span class="line">    <span class="keyword">if</span> x(<span class="built_in">i</span>) &lt; low,</span><br><span class="line">      low = x(<span class="built_in">i</span>)</span><br><span class="line">      low_index = <span class="built_in">i</span></span><br><span class="line">    <span class="keyword">elseif</span> x(<span class="built_in">i</span>) &gt; high,</span><br><span class="line">      high = x(<span class="built_in">i</span>)</span><br><span class="line">      high_index = <span class="built_in">i</span></span><br><span class="line">    endif</span><br><span class="line">  endfor</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>
<p>这样看起来没什么问题。但是却依然引出了另一个问题：一旦找出符合<code>if</code>语句的分数，程序就会立马返回并打印，然后你就发现了一大堆数字堆在那里，并只能通过肉眼筛选真正符合条件的数字。如果说明得学术一点，那就是：“<strong>打印出大量的局部最优解，并只能通过肉眼寻找全局最优解</strong>”。是不是很让人抓狂？</p>
<p>还是有解决办法的。也就是在调用的时候规定返回值：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[a, b, c, d] = filter(param)</span><br></pre></td></tr></table></figure>
<p>这样的话虽然还是会打印一大堆数字，却能够很明显地看出全局最优解的结果了。</p>
<p>当然，有函数就一定有错误处理：</p>
<figure class="highlight matlab"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="params">[low, low_index, high, high_index]</span> = <span class="title">filter</span><span class="params">(x)</span></span></span><br><span class="line">  <span class="comment">% 如果不是列向量或者行向量，报错。</span></span><br><span class="line">  <span class="keyword">if</span> <span class="built_in">isvector</span>(x),</span><br><span class="line">    error(<span class="string">"filter expects a vector"</span>)</span><br><span class="line">  endif</span><br><span class="line">  low = x(<span class="number">1</span>); high = x(<span class="number">1</span>); low_index = <span class="number">0</span>; high_index = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> <span class="built_in">i</span> = <span class="number">2</span>:<span class="built_in">length</span>(x),</span><br><span class="line">    <span class="keyword">if</span> x(<span class="built_in">i</span>) &lt; low,</span><br><span class="line">      low = x(<span class="built_in">i</span>)</span><br><span class="line">      low_index = <span class="built_in">i</span></span><br><span class="line">    <span class="keyword">elseif</span> x(<span class="built_in">i</span>) &gt; high,</span><br><span class="line">      high = x(<span class="built_in">i</span>)</span><br><span class="line">      high_index = <span class="built_in">i</span></span><br><span class="line">    endif</span><br><span class="line">  endfor</span><br><span class="line">endfunction</span><br></pre></td></tr></table></figure>
<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>如果你是<code>Windows</code>环境下的纯命令行，那么你在执行了上面提到的一些画图命令之后，还需要执行<code>hold on</code>命令让图像显示出来，而<code>close</code>命令则是关闭图像。当然，毕竟是<code>Windows</code>窗体程序，你也可以选择点击右上角的<strong>关闭窗口</strong>按钮关掉这张图片。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>代码滞销，救救码农</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/wechatpay.png" alt="sakebow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/alipay.jpg" alt="sakebow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    sakebow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/" title="建模工具：octave">https://sakebow.github.io/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7%EF%BC%9Aoctave/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/%E5%BB%BA%E6%A8%A1%E5%B7%A5%E5%85%B7/" rel="tag"> <i class="fa fa-tag"></i> 建模工具</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/07/26/hexo/hexo%E6%B7%BB%E5%8A%A0%E6%95%B0%E5%AD%A6%E5%85%AC%E5%BC%8F%E6%B8%B2%E6%9F%93%E5%99%A8/" rel="next" title="Hexo添加数学公式渲染器">
                <i class="fa fa-chevron-left"></i> Hexo添加数学公式渲染器
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/07/26/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD/%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80/%E6%A2%AF%E5%BA%A6%E4%B8%8B%E9%99%8D/" rel="prev" title="梯度下降">
                梯度下降 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>
	<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
    <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
	<script>
      var gitment = new Gitment({
        id: '<%= page.date %>',
        owner: 'sakebow',
        repo: 'git@github.com:sakebow/sakebow.github.io.git',
        oauth: {
          client_id: '5c74c5e1b67e5a5adbdf',
          client_secret: '0d352353407a32cee695d8ac619108e725919c57',
        },
      });
      gitment.render('gitment-container');
    </script>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/icon/UN.png"
                alt="sakebow" />
            
              <p class="site-author-name" itemprop="name">sakebow</p>
              <p class="site-description motion-element" itemprop="description">哪怕是狗也不想随随便便放弃看到的骨头</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">70</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sakebow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sakebowljx@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/sakebow" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/sakebow" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/sakebow" title="Sakebow的GitHub" target="_blank">Sakebow的GitHub</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.appgofast.com" title="我喜欢的VPN" target="_blank">我喜欢的VPN</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#导读"><span class="nav-number">1.</span> <span class="nav-text">导读</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#界面展示"><span class="nav-number">2.</span> <span class="nav-text">界面展示</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更换命令行"><span class="nav-number">3.</span> <span class="nav-text">更换命令行</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基于Linux的特点"><span class="nav-number">4.</span> <span class="nav-text">基于Linux的特点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#清空矩阵"><span class="nav-number">5.</span> <span class="nav-text">清空矩阵</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#快速矩阵"><span class="nav-number">6.</span> <span class="nav-text">快速矩阵</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#矩阵构造"><span class="nav-number">7.</span> <span class="nav-text">矩阵构造</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#冒号表达式"><span class="nav-number">8.</span> <span class="nav-text">冒号表达式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#个数计算"><span class="nav-number">9.</span> <span class="nav-text">个数计算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他数学函数"><span class="nav-number">10.</span> <span class="nav-text">其他数学函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据集的导入和导出"><span class="nav-number">11.</span> <span class="nav-text">数据集的导入和导出</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#统计图绘制"><span class="nav-number">12.</span> <span class="nav-text">统计图绘制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#统计图绘制样式"><span class="nav-number">13.</span> <span class="nav-text">统计图绘制样式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#散点图"><span class="nav-number">14.</span> <span class="nav-text">散点图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#柱状图"><span class="nav-number">15.</span> <span class="nav-text">柱状图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#等高线"><span class="nav-number">16.</span> <span class="nav-text">等高线</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#极坐标"><span class="nav-number">17.</span> <span class="nav-text">极坐标</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#饼状图"><span class="nav-number">18.</span> <span class="nav-text">饼状图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#选择支"><span class="nav-number">19.</span> <span class="nav-text">选择支</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#循环"><span class="nav-number">20.</span> <span class="nav-text">循环</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#函数"><span class="nav-number">21.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#其他"><span class="nav-number">22.</span> <span class="nav-text">其他</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Sakebow</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: window.location.pathname, 
            owner: 'sakebow',
            repo: 'git@github.com:sakebow/sakebow.github.io.git',
            
            lang: "" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '0d352353407a32cee695d8ac619108e725919c57',
            
                client_id: '5c74c5e1b67e5a5adbdf'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
      flOptions = {};
      
          flOptions.iconStyle = "box";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  
 
</body>
</html>
